package com.itxx.keyCase.Demo7;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.time.LocalDateTime;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TcpServer {
    public static void main(String[] args) throws IOException {
        //1.创建ServerSocket对象
        ServerSocket ss = new ServerSocket(34522);
        //2.创建io流接受数据
        //自定义线程池
        ThreadPoolExecutor executor = new ThreadPoolExecutor(20,
                20,
                5,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(10),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
        while (true) {
            //2.调用accept()阻塞方法等待客户端连接,如果有客户端链接,则返回对应的socket对象.
            Socket socket = ss.accept();
            //3.开启一个线程对象将返回的socket传入,开启多线程 [将线程start了实际上就和main方法没什么关系,main方法是一个线程,FileUpLoadSocketThread也是线程]
            executor.submit(new FileUpLoadSocketThread(socket));
        }
    }
}

class FileUpLoadSocketThread implements Runnable {
    private Socket socket;

    public FileUpLoadSocketThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        while (true) {

            BufferedInputStream bis = null;
            try {
                bis = new BufferedInputStream(socket.getInputStream());
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:\\develop\\workspace\\Advance_Code\\day15\\src\\com\\itxx\\keyCase\\server\\" + UUID.randomUUID().toString().replace("-", "") + ".jpg"));

                byte[] bytes = new byte[1024];
                int len;
                while ((len = bis.read(bytes)) != -1) {
                    bos.write(bytes, 0, len);
                }
                //4.接受完成 提醒客户端
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                bw.write("在" + LocalDateTime.now() + "上传完成");
                bw.newLine();
                bw.flush();

                //3.释放资源
                bos.close();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }


        }
    }
}
